<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="box1"></div>
    <div id="box2"></div>
    <script>

        var box1 = document.getElementById('box1')
        var box2 = document.getElementById('box2')
        //绑定按下事件
        box1.onmousedown = function (event) {
            //捕获 浏览器兼容
            if (box1.setCapture) {
                box1.setCapture();//只有ie支持

            }
            event = event || window.event
            //求出偏移量 鼠标。clentX-元素。offsetLift
            var oleft = event.clientX - box1.offsetLeft
            //求出偏移量 鼠标。clentY-元素。offsetTop
            var otop = event.clientY - box1.offsetTop


            //鼠标移动绑定onmousemove
            //给document绑定移动事件
            document.onmousemove = function (event) {
                //获取坐标位置
                event = event || window.event
                var left = event.clientX - oleft;
                var top = event.clientY - otop;

                //修改box1的位置
                box1.style.left = left + "px";
                box1.style.top = top + "px";
            }
            // 取消浏览器的默认行为  ie8 不起作用
            return false
        }
        //鼠标松开事件onmouseup
        document.onmouseup = function () {
            //取消onmousemove事件
            document.onmousemove = null;
            //取消onmousemove事件
            // document.onmouseup = null;
            //当取消时，取消事件捕获
            if (box1.releaseCapture) {
                box1.releaseCapture();//只有ie支持

            }

        }


    </script>
</body>
<style>
    #box1 {
        height: 100px;
        width: 100px;
        background-color: red;
        position: absolute;
    }

    #box2 {
        height: 100px;
        width: 100px;
        background-color: rgb(17, 0, 255);
        position: absolute;
        top: 200px;
    }
</style>

</html>